<template>
  <div class="table-container">
    <el-table :data="tableData" :height="tableHeight" :row-class-name="lockedRowClass" border size="small"
              @row-click="handleClick">
      <el-table-column align="center" label="商品" prop="attach" show-overflow-tooltip></el-table-column>
      <!-- <el-table-column prop="quantity" label="数量" align="center"></el-table-column> -->
      <el-table-column align="center" label="应付" prop="amount"></el-table-column>
      <el-table-column align="center" label="实付" prop="payAmount"></el-table-column>
      <el-table-column align="center" label="顾客" prop="memberName"></el-table-column>
      <el-table-column align="center" label="结算方式" prop="payTypeName"></el-table-column>
      <el-table-column :formatter="timeSimplify" align="center" label="结算时间" prop="payDate"></el-table-column>
    </el-table>
    <div class="statistic">
      品类：{{ saleKinds }}
      <el-divider direction="vertical"></el-divider>
      销量：{{ saleQuantity }}
      <el-divider direction="vertical"></el-divider>
      销售：{{ salePayAmount.toFixed(2) }} 元
      <el-divider direction="vertical"></el-divider>
      赠送：{{ saleGiftAmount.toFixed(2) }} 元
    </div>
    <div class="pager">
      <el-pagination :current-page="currentPage" :page-size="pageSize" :total="saleCommodityList.length"
                     layout="total, prev, pager, next" @prev-click="handlePrevClick" @next-click="handleNextClick"
                     @current-change="handleCurrentChange"></el-pagination>
    </div>
    <!-- 详情弹窗 -->
    <el-dialog :visible.sync="dialogVisible" title="消费信息详情">
      <el-form class="info-form" size="medium" status-icon>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="24"><span class="form-span">商品名称：{{ currentRow ? currentRow.attach : '' }}</span></el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">应付金额：{{ currentRow ? currentRow.amount : '' }} 元</span></el-col>
            <el-col :span="12"><span class="form-span">实付金额：{{ currentRow ? currentRow.payAmount : '' }} 元</span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">会员名称：{{ currentRow ? currentRow.memberName : '' }} </span>
            </el-col>
            <el-col :span="12"><span class="form-span">结算方式：{{ currentRow ? currentRow.payTypeName : '' }} </span>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">商品数量：{{ currentRow ? currentRow.quantity : '' }}</span></el-col>
            <el-col :span="12"><span class="form-span">结算时间：{{
                currentRow ? timeFormatter(currentRow.payDate) : ''
              }}</span></el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row :gutter="20">
            <el-col :span="12"><span class="form-span">支付状态：{{ currentRow ? currentRow.payStatusName : '' }}</span>
            </el-col>
            <el-col :span="12"><span class="form-span">促销活动：{{ currentRow ? currentRow.discountDetails : '' }}</span>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button v-show="showRefund" style="float:left;" type="danger" @click="showAuthDialog = true">退款</el-button>
        <el-button type="success" @click="printReceipt">打印小票</el-button>
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </span>
    </el-dialog>
    <check-authorize :checkKey="'/pos-client/commodity-refund'" :errMsg="'该账户无非油退款权限'" :showAuthDialog="showAuthDialog"
                     @authPass="handleRefund" @hideAuthDialog="showAuthDialog = false"></check-authorize>
  </div>
</template>
<script>
import {mapGetters} from 'vuex'
import moment from 'moment'
import {getCommodityReceiptText} from '@/utils/receipt'
import {storeRefund} from '@/api/settle'
import CheckAuthorize from './CheckAuthorize.vue'
import QRCode from 'qrcode'

export default {
  name: 'SaleCommodityRecord',
  components: {
    CheckAuthorize
  },
  data () {
    return {
      dialogVisible: false,
      currentRow: {},
      currentPage: 1,
      showAuthDialog: false
    }
  },
  computed: {
    // 销售品类
    saleKinds () {
      var oldArr = this.saleCommodityList.filter(item => item.payStatus === 1).map(item => {
        return item.commodityIds.split(';')
      })
      return new Set(oldArr.reduce((prev, curr) => (prev.concat(curr)), [])).size
    },
    // 销售总数
    saleQuantity () {
      return this.saleCommodityList.filter(item => item.payStatus === 1).reduce((pre, item) => item.quantity + pre, 0)
    },
    // 销售金额
    salePayAmount () {
      return this.saleCommodityList.filter(item => item.payStatus === 1).reduce((pre, item) => item.payAmount + pre, 0.00)
    },
    // 赠送金额
    saleGiftAmount () {
      return this.saleCommodityList.filter(item => item.payStatus === 1 && parseFloat(item.payAmount) === 0.00).reduce((pre, item) => item.amount + pre, 0.00)
    },
    tableData () {
      if (this.currentPage * this.pageSize > this.saleCommodityList.length) {
        return this.saleCommodityList.slice(this.pageSize * (this.currentPage - 1), this.saleCommodityList.length)
      } else {
        return this.saleCommodityList.slice(this.pageSize * (this.currentPage - 1), this.pageSize * this.currentPage)
      }
    },
    ...mapGetters([
      'contentHeight',
      'saleCommodityList',
      'stationId',
      'operator',
      'pageSize'
    ]),
    tableHeight () {
      return (this.contentHeight - 315) + 'px'
    },
    showRefund () {
      return this.currentRow && this.currentRow.payStatus === 1
    }
  },
  mounted () {
  },
  methods: {
    timeFormatter (time) {
      return moment(time).format('HH:mm:ss')
    },
    timeSimplify (row, column) {
      return row[column.property] ? moment(row[column.property]).format('HH:mm:ss') : ''
    },
    lockedRowClass ({row, rowIndex}) {
      return row.locked ? 'locked' : ''
    },
    handleClick (row, column, event) {
      console.log('handleClick')
      console.log(row)
      this.dialogVisible = true
      this.currentRow = row
    },
    handlePrevClick (page) {
      this.currentPage = page
    },
    handleNextClick (page) {
      this.currentPage = page
    },
    handleCurrentChange (page) {
      this.currentPage = page
    },
    printReceipt () {
      if (this.currentRow.payStatus === 1 && this.currentRow.status === 2) {
        QRCode.toDataURL(this.currentRow.uid)
          .then(url => {
            console.log(url)
            this.currentRow.qrcode = url
            this.$store.dispatch('addToReceiptList', getCommodityReceiptText(this.currentRow))
          })
          .catch(err => {
            console.error(err)
          })
      } else {
        this.$store.dispatch('addToReceiptList', getCommodityReceiptText(this.currentRow))
      }
      this.$message.success('操作成功')
    },
    handleRefund () {
      console.log('handleRefund')
      console.log(this.currentRow)
      this.$confirm('确定要发起退款操作?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        var params = JSON.parse(JSON.stringify(this.currentRow))
        params.salesman = this.operator
        storeRefund(params).then(res => {
          console.log(res)
          this.$message.success(res.msg || '退款成功！')
          this.dialogVisible = false
        }).catch(err => {
          console.log(err)
          this.$message.error(err || '退款失败！')
        })
      }).catch(() => {
        console.log('取消')
      })
    }
  }
}
</script>
<style scoped>
.table-container {
  width: 100%;
  height: 100%;
}

.form-span {
  font-family: "Helvetica Neue", Helvetica, Arial, "PingFang SC", "Hiragino Sans GB", "Heiti SC", "Microsoft YaHei", "WenQuanYi Micro Hei", sans-serif;
  font-size: 18px;
  font-weight: bold;
}

.el-form-item {
  margin-bottom: 5px;
}

.info-form {
  padding: 10px 30px;
}

.pager {
  text-align: center;
  padding: 5px;
  background: white;
}

.statistic {
  width: 100%;
  text-align: center;
  height: 30px;
  line-height: 30px;
  background: white;
  color: gray;
  border-bottom: 1px solid #EBEEF5;
}
</style>
<style>
.el-table .locked {
  background: #E6A23C;
  color: white;
}
</style>